
import subprocess
import pandas as pd
import os
import re
import math
import numpy as np
import shutil
import gradio as gr
import concurrent.futures
from tqdm import tqdm


import sys
sys.path.append('.\\Data_process\\')

from Multi_threading import run_simulation

from replace_pl import update_par_file 
from Path_completion import Path_completion

from many_file import many_file_sheet1,many_file_sheet1_2,many_file_sheet2

from read_parx import Extract_files_par

from Generate_5_10 import generate_5_10

from opt2D_TO_RawData import opt2D_to_Raw_data

from Extract_file_name import extract_fime_name
from read_xlsx_sheet2 import replace_text_in_file_sheet2_Define,replace_text_in_file_sheet2_Emitter
from read_xlsx_sheet3 import replace_text_in_file_sheet3_Commands_2
from Data_process.auto_process import dataprogress


from flask import Flask, render_template, request
from flask import jsonify

app = Flask(__name__)
from flask_bootstrap import Bootstrap  # python3.x导入方式
# from flask.bootstrap import Bootstrap  #python2.x导入方式
from flask_bootstrap import Bootstrap
from services.ex_service import say_hello

bootstrap = Bootstrap(app)

def genert_par(project_file_path,parx_file_path,PL_path,setting_file,new_sim_name):

    project_file_path=os.path.normpath(project_file_path).replace('\\', '/')

    parx_file_path=os.path.normpath(parx_file_path).replace('\\', '/')

    PL_path = os.path.normpath(PL_path).replace('\\', '/')


    setting_file = os.path.normpath(setting_file).replace('\\', '/')

    par_file='000_simulation.par'
    # par_file = os.path.normpath(par_file).replace('\\', '/')

    Extract_files_par(parx_file_path)
    print("====开始生成文件====")
    # update_par_file(par_file, new_sim_name, PL_path,setting_file)
    file_path1=par_file
    if os.path.isfile(file_path1):
        update_par_file(par_file, new_sim_name, PL_path,setting_file,project_file_path)
    print("====文件生成结束===")

    
    print("====开始进行shee2/3内容的修改===") 

    Gui_Par_Name=[]
    file_path=new_sim_name
    if os.path.isfile(file_path):
        # print("ok")
        file_par =  file_path # 替换为你的文件路径
        # file_xlsx ='C:\\Users\\admin\\Desktop\\03_simulation_example\\00 Structure\\G\\G-Simulation-Setting.xlsx'
        print("进行sheet2,Define-Emitter的替换")
        # string1=input()
        # if string1=='yes':
        start_tag1 = 'Define'
        end_tag1 = 'Emitter'
        replace_text_in_file_sheet2_Define(file_par, setting_file,start_tag1, end_tag1,2)
            


        print("进行sheet2,Emitter-Commands的替换")
        # string2=input()
        # if string2=='yes':
        start_tag2 = 'Emitter'
        end_tag2 = 'Commands'
        string_nk_path=f'{PL_path}/'
        replace_text_in_file_sheet2_Emitter(file_par, setting_file,start_tag2, end_tag2,2,string_nk_path)


        print("进行sheet3,CalcEmission-Sweep的替换")
        # string3=input()
        # if string3=='yes':
        start_tag3 = 'CalcEmission'
        end_tag3 = 'Sweep'

        # replace_text_in_file_sheet3_Commands(file_par, setting_file,start_tag3, end_tag3,3)
        replace_text_in_file_sheet3_Commands_2(file_par, setting_file,start_tag3, end_tag3,3)

        print("进行缺失路径补全")
        # string4=input()
        # if string4=='yes':
        file_path=new_sim_name
        if os.path.isfile(file_path):
            # print("ok")
            Path_completion(file_path,PL_path)
        
        
        print("进行多文件生成")
        list5=[]
        list4=[]
        # string5=input()
        # if string5=='yes':
        file_path=new_sim_name
        if os.path.isfile(file_path):
            # print("ok")
            print("进行sheet1部分多文件替换")
            # string6=input()
            # if string6=='yes':
            list5,list4=many_file_sheet1(file_path,setting_file,PL_path)
            print("开始生成。。。。。。。。")
            many_file_sheet1_2(list5,list4,file_path,setting_file)
            print("结束。。。。。。")


            print("进行sheet2部分多文件替换")
            # string7=input()
            # if string7=='yes':
            Gui_Par_Name=many_file_sheet2(file_path,setting_file,PL_path,2)



    print("开始生成(5 and 10)%")
    for lst in Gui_Par_Name:
        generate_5_10(lst, str(10), 0.9,project_file_path)
    for lst in Gui_Par_Name:
        generate_5_10(lst, str(5), 0.95,project_file_path)
    print("(5 and 10)%生成结束")


def Find_FileName(path,string1,string2):
    for filename in os.listdir(path):
        # print(filename)
        # print(type(filename))
        if string1 and string2 in filename:
            # print(filename)
            return filename
# @app.route('/')
# def hello_world():
#     return 'Hello World!'

@app.route('/')
def test():
    with app.app_context():
        return render_template('indexAgg.html')

@app.route('/api/genertPar', methods=['POST'])
def ParGenert():
    data = request.get_json()
    project_file_path=data.get('Pro_path')
    setting_path=data.get('Need_path')


    NK_path=f'{setting_path}\\00 NK'

    # R模型生成
    new_sim_name_R='R_Ref.par'

    parx_file_path=f'{setting_path}\\R'
    setting_file=f'{setting_path}\\R'

    parx_string_name=Find_FileName(f'{setting_path}\\R','R','.parx')
    parx_file_path=f'{setting_path}\\R\\{parx_string_name}'


    setting_file_name=Find_FileName(f'{setting_path}\\R','R','.xlsx')
    setting_file=f'{setting_path}\\R\\{setting_file_name}'


    genert_par(project_file_path,parx_file_path,NK_path,setting_file,new_sim_name_R)

    # G模型生成
    new_sim_name_G='G_Ref.par'

    parx_file_path=f'{setting_path}\\G'
    setting_file=f'{setting_path}\\G'

    parx_string_name=Find_FileName(f'{setting_path}\\G','G','.parx')
    parx_file_path=f'{setting_path}\\G\\{parx_string_name}'


    setting_file_name=Find_FileName(f'{setting_path}\\G','G','.xlsx')
    setting_file=f'{setting_path}\\G\\{setting_file_name}'


    genert_par(project_file_path,parx_file_path,NK_path,setting_file,new_sim_name_G)



    # B模型生成
    new_sim_name_B='B_Ref.par'

    parx_file_path=f'{setting_path}\\B'
    setting_file=f'{setting_path}\\B'

    parx_string_name=Find_FileName(f'{setting_path}\\B','B','.parx')
    parx_file_path=f'{setting_path}\\B\\{parx_string_name}'


    setting_file_name=Find_FileName(f'{setting_path}\\B','B','.xlsx')
    setting_file=f'{setting_path}\\B\\{setting_file_name}'


    genert_par(project_file_path,parx_file_path,NK_path,setting_file,new_sim_name_B)


    return jsonify({'message': 'successed'})


class Ref510:
    def __init__(self):
        self.count = 0
        self.number_par=0

    def Ref_5_10_2(self,string1,MAX_THREADS,out_put,setfos_dir,file_number,runsim):
        folder_path = f'.\\{string1}'

        # folder_path = '.\\two_par_result'
        list1 = [filename for filename in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, filename))]
        self.number_par=len(list1)

        # 使用 ThreadPoolExecutor 来控制并发线程数
        with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
            futures = []
            # for item in list1:
            for i,item in tqdm(enumerate(list1), desc=f"Processing {string1}", unit='file'):
                # out_put_new=os.path.join(out_put,str(random.randint(1,file_number)))
                out_put_new=os.path.join(out_put,str(i%file_number))
                if not os.path.exists(out_put_new):
                    os.makedirs(out_put_new)
                futures.append(executor.submit(run_simulation, item, folder_path,setfos_dir, out_put_new, runsim))

            # 等待所有线程完成
            # for future in concurrent.futures.as_completed(futures):
            for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures), desc="Waiting for simulations", unit='simulation'):
                future.result()
                self.count=self.count+1

ref510=Ref510()
@app.route('/api/beginSim', methods=['POST'])
def BeginSimulatino():
    data = request.get_json()
    setfos_path=data.get('Setfos_path')
    setfos_result_path=data.get('Result_file_path')

    setfos_path = os.path.normpath(setfos_path).replace('\\', '\\\\')
    setfos_path=setfos_path+'\\\\'
    print(setfos_path)

    setfos_result_path = os.path.normpath(setfos_result_path).replace('\\', '\\\\')
    setfos_result_path=setfos_result_path+'\\\\'+'Data'+'\\\\'
    print(setfos_result_path)


    MAX_THREADS = int(data.get('Thread_num'))


    file_number = int(data.get('Result_file_num'))

    print("开始仿真........")
    runsim = True


    number=data.get('select_Ref')
    if number == '1':
        ref510.Ref_5_10_2('finally_par_result', MAX_THREADS, setfos_result_path, setfos_path, file_number,runsim)
        ref510.Ref_5_10_2('two_par_result', MAX_THREADS, setfos_result_path, setfos_path, file_number,runsim)
        print('Ref仿真结束')
    if number == '2':
        ref510.Ref_5_10_2('two_par_result', MAX_THREADS, setfos_result_path, setfos_path, file_number,runsim)
        print('Ref仿真结束')



@app.route('/api/get_count',methods=['POST'])
def get_count():
    return jsonify({'count': ref510.count/ref510.number_par})


@app.route('/api/beginDataProg',methods=['POST'])
def begin_Data_progress():
    number_file=opt2D_to_Raw_data()

    finally_name,finally_name_only_Ref=extract_fime_name()


    return jsonify({'number_file':number_file,'finally_name':finally_name,'finally_name_only_Ref':finally_name_only_Ref})

@app.route('/api/DataProgress',methods=['POST'])
def beginning_Data_progress():
    dataprogress()
    return jsonify({'message': 'successed'})



if __name__ == '__main__':
    # app.run() 默认5000
    app.run(debug=True, host="0.0.0.0", port=8086)
